package com.mikewoo.nio;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;

/**
 * Title: SocketChannelDemo.java
 * Description: SocketChannel客户端 
 * 
 * author     Phantom
 * date       2016年5月19日 下午1:35:05
 * @version    1.0.0
 */
public class SocketChannelDemo {
	
	public static void startClient() throws Exception {
		SocketChannel socketChannel = SocketChannel.open();
		socketChannel.connect(new InetSocketAddress("localhost", 8999));
		//socketChannel.configureBlocking(false);
		
		String request = "hello socketServer 测试";
		ByteBuffer byteBuffer = ByteBuffer.wrap(request.getBytes("UTF-8"));
		int size = socketChannel.write(byteBuffer);
		System.out.println("成功写入" + size + "字节");
		byteBuffer.clear();
		
		ByteBuffer rbuffer = ByteBuffer.allocate(48);
		int rsize = socketChannel.read(rbuffer);
		while (rsize > 0) {
			rbuffer.flip();
			Charset charset = Charset.forName("UTF-8");
			System.out.println(charset.newDecoder().decode(rbuffer));
			rbuffer.clear();
			
			rsize = socketChannel.read(rbuffer);
		}
		rbuffer.clear();
		socketChannel.close();
	}
	
	public static void main(String[] args) throws Exception {
		startClient();
	}
}
